package org.ilc.push.socket;

/**
 * 心跳包
 *
 * @author xumin
 *
 */
class HeartWorker extends Thread {

    private boolean running = false;
    private SocketConnection conn;

    public HeartWorker(SocketConnection conn) {
        this.conn = conn;
    }

    /**
     * 创建心跳包
     *
     * @return
     */
    byte[] createHeartData() {
        IHeader header = new Header ();
        header.addHeader(IHeader.HEAD_AUTH_USER_KEY, conn.getAuthUser());
        header.addHeader(IHeader.HEAD_AUTH_PWD_KEY, conn.getAuthPwd());
        header.addHeader(IHeader.HEAD_CONTENT_LENGTH_KEY, "0");
        header.addHeader ("auth-type", conn.getAuthType ());
        header.addHeader ("auth-version", conn.getAuthVersion ());


//        System.out.println (header.toString ());
        return header.toString().getBytes();
    }

    public void run() {
        byte[] heartData = createHeartData();
        try {
            while (running) {
                conn.sendData(heartData,null);
                try {
//                    System.out.println ("heart..");
                    Thread.sleep(conn.getHeartSleepTime());
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            heartData = null;

        }

    }

    public void stopWorker() {
        this.running = false;
    }

    public void startWorker() {
        if (running) {
            return;
        }
        this.running = true;
        this.start();
    }
}
